package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyThemeQuery;
import cn.wolfcode.wolf2w.repository.StrategyThemRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
// @Transactional
public class StrategyThemServiceImpl implements IStrategyThemeService{
    @Autowired
    private StrategyThemRepository strategyThemRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);
        strategyThemRepository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        strategyThemRepository.deleteById(id);
    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        // 当实现修改操作时,如果数据库列表中的字段和 domain里面的一致就
        // 不用先查后修改操作.

        /*String id = strategyTheme.getId();
        StrategyTheme newStrategyTheme = mongoTemplate.findById(id, StrategyTheme.class);*/
        strategyThemRepository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        return strategyThemRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {

        return strategyThemRepository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQuery qo) {
        Query query = new Query();
        long totalCount = mongoTemplate.count(query, StrategyTheme.class);
        if (totalCount == 0){
            // 返回一个空白页面
            return Page.empty();
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");
        query.with(pageable);
        List<StrategyTheme> list = mongoTemplate.find(query, StrategyTheme.class);
        return new PageImpl<>(list,pageable,totalCount);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {

        if (StringUtils.hasLength(strategyTheme.getId())){
            this.update(strategyTheme);
        }else{
            this.save(strategyTheme);
        }
    }
}
